package com.deli.talkbetter;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.PopupWindow;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.deli.talkbetter.databinding.FragmentReadingBinding;
import com.deli.talkbetter.llm.MaaS;
import com.deli.talkbetter.llm.ReadingPassage;
import com.deli.talkbetter.llm.ReadingQuestion;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReadingFragment extends Fragment {

    private FragmentReadingBinding binding;
    private MaaS maas;
    private List<ReadingPassage> passages;
    private int currentPassageIndex = 0;
    private List<RadioGroup[]> allRadioGroups; // 保存所有题目的RadioGroup引用
    private List<Boolean[]> questionAnswered; // 每篇文章每道题的答题状态
    private Handler progressHandler;
    private Runnable progressRunnable;
    private int progress = 0;
    private final int maxProgress = 25; // 25秒满格
    private PopupWindow translationPopup;
    private Handler translationHandler;
    private Runnable translationRunnable;

    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {

        binding = FragmentReadingBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 初始化 MaaS 实例
        maas = new MaaS();

        // 设置回调
        maas.setReadingPassagesCallback(new MaaS.ReadingPassagesCallback() {
            @Override
            public void onReadingPassagesLoaded(List<ReadingPassage> loadedPassages) {
                stopProgress(); // 停止进度更新
                passages = loadedPassages;
                if (passages != null && !passages.isEmpty()) {
                    currentPassageIndex = 0;
                    allRadioGroups = new ArrayList<>();
                    questionAnswered = new ArrayList<>();
                    requireActivity().runOnUiThread(() -> {
                        binding.progressBar.setVisibility(View.GONE);
                        displayPassage();
                    });
                }
            }

            @Override
            public void onError(String error) {
                stopProgress(); // 停止进度更新
                requireActivity().runOnUiThread(() -> {
                    binding.progressBar.setVisibility(View.GONE);
                    Toast.makeText(requireContext(), "获取阅读理解失败: " + error, Toast.LENGTH_LONG).show();
                });
            }
        });

        // 调用大模型获取阅读理解内容
        maas.fetchReadingPassagesFromAPI(requireContext());
        startProgress(); // 开始进度更新

        // 设置上一篇按钮点击事件
        binding.prevPassageButton.setOnClickListener(v -> showPrevPassage());

        // 设置下一篇按钮点击事件
        binding.nextPassageButton.setOnClickListener(v -> showNextPassage());
    }
    
    private void startProgress() {
        binding.progressBar.setVisibility(View.VISIBLE);
        binding.progressBar.setMax(maxProgress); // 设置最大进度
        binding.progressBar.setProgress(0); // 初始进度为0
        
        progress = 0;
        progressHandler = new Handler(Looper.getMainLooper());
        progressRunnable = new Runnable() {
            @Override
            public void run() {
                progress++;
                binding.progressBar.setProgress(progress);
                
                if (progress < maxProgress) {
                    // 每秒更新一次进度
                    progressHandler.postDelayed(this, 1000);
                }
            }
        };
        
        // 开始进度更新
        progressHandler.postDelayed(progressRunnable, 1000);
    }
    
    private void stopProgress() {
        if (progressHandler != null && progressRunnable != null) {
            progressHandler.removeCallbacks(progressRunnable);
            progressHandler = null;
            progressRunnable = null;
        }
    }

    private void displayPassage() {
        if (passages != null && !passages.isEmpty() && currentPassageIndex < passages.size()) {
            ReadingPassage passage = passages.get(currentPassageIndex);

            // 显示文章标题
            binding.passageTitle.setText(passage.getTitle());

            // 显示文章内容，并添加点击事件处理
            SpannableString contentSpannable = new SpannableString(passage.getContent());
            addClickSpans(contentSpannable, passage.getContent());
            binding.passageContent.setText(contentSpannable);
            binding.passageContent.setMovementMethod(LinkMovementMethod.getInstance());

            // 清除之前的题目
            binding.questionsContainer.removeAllViews();
            
            // 初始化当前文章的答题状态
            Boolean[] currentPassageAnswers = new Boolean[passage.getQuestions().length];
            for (int i = 0; i < currentPassageAnswers.length; i++) {
                currentPassageAnswers[i] = false;
            }
            questionAnswered.add(currentPassageAnswers);
            
            // 创建当前文章所有题目的RadioGroup数组
            RadioGroup[] currentRadioGroups = new RadioGroup[passage.getQuestions().length];
            allRadioGroups.add(currentRadioGroups);

            // 显示所有题目
            displayAllQuestions();

            // 更新导航按钮状态
            updateNavigationButtons();
        }
    }
    
    // 为文本中的单词添加点击事件
    private void addClickSpans(SpannableString spannableString, String text) {
        // 使用正则表达式匹配英文单词
        Pattern wordPattern = Pattern.compile("[a-zA-Z]+");
        Matcher matcher = wordPattern.matcher(text);
        
        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            String word = matcher.group();
            
            ClickableSpan clickableSpan = new ClickableSpan() {
                @Override
                public void onClick(@NonNull View widget) {
                    // 获取单词翻译
                    fetchAndShowTranslation(word, widget);
                }
                
                @Override
                public void updateDrawState(@NonNull TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setUnderlineText(false); // 不显示下划线
                }
            };
            
            spannableString.setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    
    // 获取并显示单词翻译
    private void fetchAndShowTranslation(String word, View view) {
        // 直接获取翻译，不显示加载提示
        // 取消之前的隐藏翻译任务（如果有的话）
        if (translationHandler != null && translationRunnable != null) {
            translationHandler.removeCallbacks(translationRunnable);
        }
        
        // 获取翻译
        maas.fetchWordTranslation(requireContext(), word, new MaaS.TranslationCallback() {
            @Override
            public void onTranslationLoaded(String translation) {
                requireActivity().runOnUiThread(() -> {
                    // 显示翻译结果PopupWindow
                    TextView translationText = new TextView(requireContext());
                    translationText.setText(translation);  // 直接显示翻译结果，不加前缀
                    translationText.setBackgroundColor(Color.WHITE);
                    translationText.setPadding(20, 20, 20, 20);
                    
                    if (translationPopup != null && translationPopup.isShowing()) {
                        translationPopup.dismiss();
                    }
                    
                    translationPopup = new PopupWindow(translationText, 
                            ViewGroup.LayoutParams.WRAP_CONTENT, 
                            ViewGroup.LayoutParams.WRAP_CONTENT);
                    translationPopup.setOutsideTouchable(true);
                    translationPopup.setFocusable(false);
                    translationPopup.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
                    
                    // 使用showAsDropDown来更精确地定位PopupWindow
                    translationPopup.showAsDropDown(view, 50, -100);
                    
                    // 2秒后自动隐藏翻译
                    scheduleHideTranslation();
                });
            }
            
            @Override
            public void onError(String error) {
                requireActivity().runOnUiThread(() -> {
                    // 显示错误信息
                    TextView errorText = new TextView(requireContext());
                    errorText.setText("获取 \"" + word + "\" 的翻译失败: " + error);
                    errorText.setBackgroundColor(Color.WHITE);
                    errorText.setPadding(20, 20, 20, 20);
                    
                    if (translationPopup != null && translationPopup.isShowing()) {
                        translationPopup.dismiss();
                    }
                    
                    translationPopup = new PopupWindow(errorText, 
                            ViewGroup.LayoutParams.WRAP_CONTENT, 
                            ViewGroup.LayoutParams.WRAP_CONTENT);
                    translationPopup.setOutsideTouchable(true);
                    translationPopup.setFocusable(false);
                    translationPopup.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
                    
                    // 使用showAsDropDown来更精确地定位PopupWindow
                    translationPopup.showAsDropDown(view, 50, -100);
                    
                    // 2秒后自动隐藏翻译
                    scheduleHideTranslation();
                });
            }
        });
    }
    
    // 安排隐藏翻译
    private void scheduleHideTranslation() {
        translationHandler = new Handler(Looper.getMainLooper());
        translationRunnable = new Runnable() {
            @Override
            public void run() {
                if (translationPopup != null && translationPopup.isShowing()) {
                    translationPopup.dismiss();
                }
            }
        };
        translationHandler.postDelayed(translationRunnable, 2000); // 2秒后隐藏
    }
    
    // 隐藏翻译
    private void hideTranslation() {
        if (translationPopup != null && translationPopup.isShowing()) {
            translationPopup.dismiss();
        }
        if (translationHandler != null && translationRunnable != null) {
            translationHandler.removeCallbacks(translationRunnable);
            translationHandler = null;
            translationRunnable = null;
        }
    }

    private void displayAllQuestions() {
        if (passages != null && !passages.isEmpty() && currentPassageIndex < passages.size()) {
            ReadingPassage passage = passages.get(currentPassageIndex);
            ReadingQuestion[] questions = passage.getQuestions();

            if (questions != null) {
                RadioGroup[] currentRadioGroups = allRadioGroups.get(currentPassageIndex);
                
                for (int i = 0; i < questions.length; i++) {
                    ReadingQuestion currentQuestion = questions[i];

                    // 创建题目容器
                    LinearLayout questionLayout = new LinearLayout(requireContext());
                    questionLayout.setOrientation(LinearLayout.VERTICAL);
                    questionLayout.setLayoutParams(new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT));
                    questionLayout.setPadding(0, 16, 0, 16);

                    // 显示题目序号和内容，并添加点击事件处理
                    TextView questionTextView = new TextView(requireContext());
                    String questionText = "题目 " + (i + 1) + ": " + currentQuestion.getQuestion();
                    SpannableString questionSpannable = new SpannableString(questionText);
                    addClickSpans(questionSpannable, questionText);
                    questionTextView.setText(questionSpannable);
                    questionTextView.setMovementMethod(LinkMovementMethod.getInstance());
                    questionTextView.setTextSize(16);
                    questionTextView.setLayoutParams(new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT));
                    questionLayout.addView(questionTextView);

                    // 创建选项组
                    RadioGroup optionsGroup = new RadioGroup(requireContext());
                    optionsGroup.setLayoutParams(new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT));
                    optionsGroup.setPadding(0, 8, 0, 16);
                    
                    // 保存RadioGroup引用
                    currentRadioGroups[i] = optionsGroup;

                    // 添加选项
                    String[] options = currentQuestion.getOptions();
                    for (int j = 0; j < options.length; j++) {
                        RadioButton option = new RadioButton(requireContext());
                        // 为选项文本添加可点击的单词翻译功能
                        SpannableString optionSpannable = new SpannableString(options[j]);
                        addClickSpansToOptions(optionSpannable, options[j]);
                        option.setText(optionSpannable);
                        option.setId(View.generateViewId());
                        option.setTextSize(16);
                        option.setPadding(0, 8, 0, 8);
                        option.setMovementMethod(LinkMovementMethod.getInstance());
                        optionsGroup.addView(option);
                    }

                    questionLayout.addView(optionsGroup);

                    // 添加到题目容器
                    binding.questionsContainer.addView(questionLayout);
                    
                    // 为选项组设置监听器
                    final int questionIndex = i;
                    optionsGroup.setOnCheckedChangeListener((group, checkedId) -> checkAnswer(questionIndex));
                }
            }
        }
    }
    
    // 为选项文本中的单词添加点击事件（排除选项标识符A、B、C、D）
    private void addClickSpansToOptions(SpannableString spannableString, String text) {
        // 使用正则表达式匹配英文单词
        Pattern wordPattern = Pattern.compile("[a-zA-Z]+");
        Matcher matcher = wordPattern.matcher(text);
        
        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            String word = matcher.group();
            
            // 检查是否是选项标识符（位于开头的单个字母A、B、C、D）
            boolean isOptionIdentifier = (start == 0 && end == 1 && 
                (word.equals("A") || word.equals("B") || word.equals("C") || word.equals("D")));
            
            // 如果是选项标识符，则跳过添加点击事件
            if (isOptionIdentifier) {
                continue;
            }
            
            ClickableSpan clickableSpan = new ClickableSpan() {
                @Override
                public void onClick(@NonNull View widget) {
                    // 获取单词翻译
                    fetchAndShowTranslation(word, widget);
                }
                
                @Override
                public void updateDrawState(@NonNull TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setUnderlineText(false); // 不显示下划线
                }
            };
            
            spannableString.setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }

    private void updateNavigationButtons() {
        if (passages == null || passages.isEmpty()) {
            binding.navigationButtons.setVisibility(View.GONE);
            return;
        }

        // 更新文章导航按钮状态
        binding.prevPassageButton.setEnabled(currentPassageIndex > 0);
        binding.nextPassageButton.setEnabled(currentPassageIndex < passages.size() - 1);

        // 显示导航按钮
        binding.navigationButtons.setVisibility(View.VISIBLE);
    }

    private void showPrevPassage() {
        if (currentPassageIndex > 0) {
            currentPassageIndex--;
            displayPassage();
        }
    }

    private void showNextPassage() {
        if (passages != null && currentPassageIndex < passages.size() - 1) {
            currentPassageIndex++;
            displayPassage();
        }
    }

    private void checkAnswer(int questionIndex) {
        if (passages == null || passages.isEmpty() || currentPassageIndex >= passages.size()) {
            return;
        }

        ReadingPassage passage = passages.get(currentPassageIndex);
        ReadingQuestion[] questions = passage.getQuestions();

        if (questions == null || questionIndex >= questions.length) {
            return;
        }

        ReadingQuestion currentQuestion = questions[questionIndex];
        RadioGroup optionsGroup = allRadioGroups.get(currentPassageIndex)[questionIndex];
        int selectedId = optionsGroup.getCheckedRadioButtonId();

        if (selectedId == -1) {
            return;
        }

        // 获取选中的选项索引
        int selectedIndex = -1;
        for (int i = 0; i < optionsGroup.getChildCount(); i++) {
            if (optionsGroup.getChildAt(i).getId() == selectedId) {
                selectedIndex = i;
                break;
            }
        }

        // 标记题目已答
        questionAnswered.get(currentPassageIndex)[questionIndex] = true;

        // 显示答案结果
        String[] options = currentQuestion.getOptions();
        String correctAnswer = options[currentQuestion.getCorrectAnswerIndex()];

        String resultText;
        if (selectedIndex == currentQuestion.getCorrectAnswerIndex()) {
            resultText = "回答正确！";
        } else {
            resultText = "回答错误！正确答案是: " + correctAnswer;
        }

        // 在选项组下方显示结果
        TextView resultTextView = new TextView(requireContext());
        resultTextView.setText(resultText);
        resultTextView.setTextSize(14);
        resultTextView.setPadding(0, 8, 0, 4);
        if (selectedIndex == currentQuestion.getCorrectAnswerIndex()) {
            resultTextView.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
        } else {
            resultTextView.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
        }
        
        // 查找是否已存在结果TextView，如果存在则移除
        View existingResult = optionsGroup.getTag() != null ? 
            (View) optionsGroup.getTag() : null;
        if (existingResult != null && existingResult.getParent() != null) {
            ((ViewGroup) existingResult.getParent()).removeView(existingResult);
        }
        
        // 添加新的结果TextView
        ViewGroup parent = (ViewGroup) optionsGroup.getParent();
        parent.addView(resultTextView);
        optionsGroup.setTag(resultTextView);

        // 显示解析
        TextView explanationTextView = new TextView(requireContext());
        explanationTextView.setText("解析: " + currentQuestion.getExplanation());
        explanationTextView.setTextSize(14);
        explanationTextView.setPadding(0, 4, 0, 8);
        
        // 查找是否已存在解析TextView，如果存在则移除
        Object tag = optionsGroup.getTag(R.id.explanation_tag);
        if (tag != null && tag instanceof View) {
            View existingExplanation = (View) tag;
            if (existingExplanation.getParent() != null) {
                ((ViewGroup) existingExplanation.getParent()).removeView(existingExplanation);
            }
        }
        
        parent.addView(explanationTextView);
        optionsGroup.setTag(R.id.explanation_tag, explanationTextView);
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        stopProgress(); // 确保在视图销毁时停止进度更新
        hideTranslation(); // 隐藏翻译
        binding = null;
    }
}